<template>
  <div class="avatar-container">
    <el-avatar :src="avatar" :size="100" @click="handleAvatarClick"></el-avatar>
    <input type="file" ref="fileInput" @change="handleFileChange" style="display: none" />
  </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import { uploadAvatar } from '@/apis/user'; // 假设你有一个 API 调用函数

const props = defineProps({
  initialAvatar: String,
});

const avatar = ref(props.initialAvatar); // 使用传入的初始头像路径
const fileInput = ref(null);

const handleAvatarClick = () => {
  fileInput.value.click();
};

const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (file) {
    const formData = new FormData();
    formData.append('avatarfile', file);

    try {
      await uploadAvatar(formData);
    } catch (error) {
      ElMessage.error('请求出错');
    }
  }
};

console.log(props.initialAvatar)

// 监听初始头像变化
watch(() => props.initialAvatar, (newAvatar) => {
  avatar.value = newAvatar;
  console.log(newAvatar)
});
</script>

<style scoped>
.avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  margin-bottom: 2vh;
}
</style>
